<template>
	<view>

		<view class="cu-chat">
	
      
      <view class="" v-for="(item,index) in msgList" :key="index">
        <!-- AI消息 -->
        <view v-if="item.my == false"  class="cu-item ai-item" >
        	<view class="flex flex-direction align-center">
        		<image class="cu-avatar round chat-avatar" src="https://www.iwangbang.com/skin/wx_mp_aixz/logo.png">
        		<text  class="cuIcon-title" :class="[statusColor]"></text>
        	</view>
        	<view class="main" style="margin: 0 30rpx;">
        		<view class="content shadow" @click="">
              <text class="">{{item.type == 'word'? item.msg : ''}}</text>
        			<image v-if="item.type == 'word' ? false : true" class="uimage" :src="item.type == 'word' ? '' : item.msg" @click="showImage(item.msg)"></image>
              <view v-if="item.type == 'word' ? false : true" class="watermark">AI作图</view>
        		</view>
            
        	</view>
          <view class="repetition" v-if="item.type == 'word' ? false : true" @click="redraw">
            <uni-icons type="refreshempty" size="30"></uni-icons>
             <view class="" @click="">重画</view>
          </view>
          
    
        </view>
          
        <!-- 用户消息 -->
        <view  v-if="item.my == true"  class="cu-item self" >
        	<view class="main">  
        		<view class="content bg-cyan shadow yhmsg" @click="">
        			<text>{{item.msg}}</text>
        		</view>
        	</view>
        	<image class="cu-avatar round" :src="headimg == '' ? 'https://www.iwangbang.com/skin/wx_mp_aixz/navigation/my.png' : headimg">
        </view>  
      </view>


		</view>
<!-- cu-bar foot input -->
		<view class=" cu-bar foot input" :style="[{bottom:inputBottom}]">
		<!-- 	<input   v-model="describe" class="solid padding-lr" :adjust-position="false" :focus="false" maxlength="1000"
				cursor-spacing="0" :placeholder="loading ? 'AI正在思考中，请稍后~' : '用一句简短的话描述您的问题'"
			 @confirm="sendMsg('nsg')"></input> -->
       
       <textarea class="asfasd padding-lr" v-model="describe" :style="{height: textheight,maxHeight:textmaxHeight}" :disable-default-padding='true'  name="" id="" cols="30" rows="10" :auto-height="fsddfsd" :fixed="true" @linechange="linechange" maxlength="-1" 
         @confirm="sendMsg('nsg')" :placeholder="loading ? 'AI正在思考中，请稍后~' : '用一句简短的话描述您的问题'" cursor-spacing="20" :adjust-position="false" :focus="false" :show-confirm-bar='false'></textarea>
       
<view class="action">
				<!-- <text class="cuIcon-emojifill text-grey"></text> -->
			</view>
			<button class="cu-btn bg-cyan shadow" :disabled="loading" @click="sendMsg('nsg')">
				<text class="cuIcon-loading2 cuIconfont-spin" ></text>发送
			</button>
		</view> 
		
    <aidialogue ref="aidialo" @backHome='backHome'></aidialogue>
	</view>
</template>   

<script>
  import  aidialogue  from '../../components/aichat/aichat.vue'
	export default {
    components:{
      aidialogue
    },
    onShareTimeline:function(res){
          return {
            title: '小帮观影，我的AI影评顾问',
            imageUrl:'https://www.iwangbang.com/skin/wx_mp_xbgy/share.jpg',
            query: "inviteCode="+uni.getStorageSync('wbyun_icode')
          }
        },
    onShareAppMessage(res) {
      console.log(res);
      console.log(uni.getStorageSync('wbyun_icode'));
      return {
            title: '小帮观影，我的AI影评顾问',
            imageUrl:'https://www.iwangbang.com/skin/wx_mp_xbgy/share.jpg',
            path: '/pages/index/index?inviteCode=' + uni.getStorageSync('wbyun_icode')
          }
    },
		data() {
			return { 
        textheight:'90rpx',
        textmaxHeight:'90rpx',
				loading: false,
        aisse:"",
        msgList:[
   
        ],
				msgContent: "",
				describe: "", 
				inputBottom: 0,
				bottomFuncShow: false,
				chatAsset: {},
				assetType: 'n',
				statusColor: 'text-red',
				statusTimer: null,
				msgLoading: false,
        usertxt:'',
        typedText:'',
        currentIndex:0,
        safe:0,
        headimg:'',
        imgrep:''
        
			}
		},
		computed: {
      
		},
		watch: {
            
		},
		 onShow() {
       this.headimg = uni.getStorageSync('wbyun_headimg')
       console.log(this.headimg,'222');
        uni.getSystemInfo({
          success:(res)=> {
            console.log(res.safeArea,res.screenHeight);
          let tabBarHeight =  res.screenHeight - res.safeArea.bottom
          console.log(tabBarHeight);
          this.safe = tabBarHeight + 180
          }
        })
         uni.onKeyboardHeightChange(res => {
           if(res.height !== 0) {
             this.inputBottom = res.height   +'px' 
             console.log(this.inputBottom,'1111');
           }else {
             this.inputBottom = res.height +'px'
           }
           
           console.log(res.height)
         })
		},
    onLoad(e){
      console.log(e);
      if(e.text !== undefined) {
        this.sendMsg(e.text)
        this.loading = true
      }
      　
    },
		onHide() { 

		}, 
    mounted() {
  
    },
		methods: {   
      // 打字输出流
      startTyping(e,id,k) {
        let text = e
        this.msgList.map(item => {
          const timer = setInterval(() => {
            if(item.id == id) {
              if(e[this.currentIndex] == undefined) {
                clearInterval(timer);
                return 
              }else {
                item.msg += text[this.currentIndex]
                this.currentIndex++; 
              }
              }
            
          }, 100);
        })
      
      },
      linechange(e) {
        console.log(e.detail);
         if(e.detail.lineCount == 1) {
           this.textheight = '90rpx'
           this.textmaxHeight = '90rpx'
        }else if(e.detail.lineCount == 2) {
          this.textheight = '120rpx'
          this.textmaxHeight= '120rpx'
        }else if(e.detail.lineCount == 3) {
          this.textheight = '157rpx'
          this.textmaxHeight= '157rpx'
        }else
        console.log(this.textheight);
      },
			 sendMsg(e) {
			          if(uni.getStorageSync('wbyun_token')==null || uni.getStorageSync('wbyun_token')==''){
			            	uni.navigateTo({
			            		url:'/pagesA/tellogin/tellogin'
			            	})
			             return
			            }
			        if(e !== 'nsg'){
			          this.describe = e
			        }
			        const regex = /^\s*$/;
			        if(this.describe == '' || regex.test(this.describe)) {
			          uni.showToast({
			          	title: '请先输入您的问题!',
			          	icon: 'none'
			          });
			          return
			        }
			        let txt = ''
			        this.loading = true
              this.imgrep = this.describe
			        this.tautology = this.describe
			        txt = this.describe
			         this.describe = ''
			         this.msgList.push({
			           msg:txt,
			           my:true
			         })
			         this.msgList.push({
			           msg:'',
			           my:false,
			           type:'word'
			         })
			         
			         this.msgList.map((item,index)=> {
			           if(index == this.msgList.length -1) { 
			             const timer = setInterval(() => {
			                   let text = '小猪正在思考中请稍等...'
			                   item.msg += text[this.currentIndex]
			                   this.currentIndex++; 
			                   if(this.currentIndex == text.length) {
			                     clearInterval((timer))
			                     return
			                   }
			             }, 50);
			           }
			         })
			         this.currentIndex = 0
			         uni.request({
			         	url: getApp().globalData.apiDomain+'ai/draw',
			         	method: 'POST',
			         	header: {
			         		'content-type': 'application/x-www-form-urlencoded', //自定义请求头信息
			         		'token': uni.getStorageSync('wbyun_token'),
			             'wbapp':'weixin_mp_xbgy'
			         	},
			         	data: {
                   'task': 'txt2img.sd',
			             'text':txt,
			             'vpsoft':'ai_hyz'
			         	},
			         	dataType: 'json',
			         	success:  res => {
			             console.log(res);
			         		if (res.data.code == 200) {
			               this.getdrawing(res.data.datas.uid)
			         			return;
			         		}else if(res['data']['code'] == '100500') {
			               uni.showToast({
			               	title:res['data']['msg'],
			               	icon: 'none'
			               });
			               uni.setStorageSync('wbyun_token','');
			               uni.setStorageSync('wbyun_username','');
			               uni.setStorageSync('wbyun_headimg','');
			               uni.setStorageSync('wbyun_tel','');
			               uni.setStorageSync('wbyun_icode','');
			               uni.navigateTo({
			               	url:'/pagesA/tellogin/tellogin'
			               })
			             }else if(res['data']['code'] == '519') {
			                   setTimeout(()=> {
			                     this.msgList.map((item,index) => {
			                       if(index == this.msgList.length -1) {
			                         item.msg = res['data']['msg']
			                       }
			                     })
			                     this.loading = false
			                     uni.showToast({
			                     	title: res['data']['msg'],
			                     	icon: 'none',
			                       duration: 5000
			                     });
			                     
			                     setTimeout(()=> {
			                       uni.navigateTo({
			                         url: '/pagesB/subson/subson/invite',
			                        
			                       });
			                     },2000)
			                   },1500)
			                   
			                 } else { 
			               setTimeout(()=> {
			                 this.msgList.map((item,index) => {
			                   if(index == this.msgList.length -1) {
			                     item.msg = res['data']['msg']
			                   }
			                 })
			               },1500)
			         			uni.showToast({
			         				title: res['data']['msg'],
			         				icon: 'none'
			         			});
			               this.loading = false
			         		}
			         	},
			         	fail: () => {},
			         	complete: () => {
			         	}
			         });
			          
			 			},
            redraw() {
              console.log(this.imgrep);
              this.loading = true
              this.msgList.push({
                msg:this.imgrep,
                my:true
              })
              this.msgList.push({
                msg:'',
                my:false,
                type:'word'
              })
              
              this.msgList.map((item,index)=> {
                if(index == this.msgList.length -1) { 
                  const timer = setInterval(() => {
                        let text = '小猪正在思考中请稍等...'
                        item.msg += text[this.currentIndex]
                        this.currentIndex++; 
                        if(this.currentIndex == text.length) {
                          clearInterval((timer))
                          return
                        }
                  }, 50);
                }
              })
              this.currentIndex = 0
              uni.request({
              	url: getApp().globalData.apiDomain+'ai/draw',
              	method: 'POST',
              	header: {
              		'content-type': 'application/x-www-form-urlencoded', //自定义请求头信息
              		'token': uni.getStorageSync('wbyun_token'),
                  'wbapp':'weixin_mp_xbgy'
              	},
              	data: {
                  'task': 'txt2img.sd',
                  'text':this.imgrep,
                  'vpsoft':'ai_hyz'
              	},
              	dataType: 'json',
              	success:  res => {
                  console.log(res);
              		if (res.data.code == 200) {
                    this.getdrawing(res.data.datas.uid)
              			return;
              		}else if(res['data']['code'] == '100500') {
                    uni.showToast({
                    	title:res['data']['msg'],
                    	icon: 'none'
                    });
                    uni.setStorageSync('wbyun_token','');
                    uni.setStorageSync('wbyun_username','');
                    uni.setStorageSync('wbyun_headimg','');
                    uni.setStorageSync('wbyun_tel','');
                    uni.setStorageSync('wbyun_icode','');
                    uni.navigateTo({
                    	url:'/pagesA/tellogin/tellogin'
                    })
                  }else if(res['data']['code'] == '519') {
                        setTimeout(()=> {
                          this.msgList.map((item,index) => {
                            if(index == this.msgList.length -1) {
                              item.msg = res['data']['msg']
                            }
                          })
                          this.loading = false
                          uni.showToast({
                          	title: res['data']['msg'],
                          	icon: 'none',
                            duration: 5000
                          });
                          
                          setTimeout(()=> {
                            uni.navigateTo({
                              url: '/pagesB/subson/subson/invite',
                             
                            });
                          },2000)
                        },1500)
                        
                      } else { 
                    setTimeout(()=> {
                      this.msgList.map((item,index) => {
                        if(index == this.msgList.length -1) {
                          item.msg = res['data']['msg']
                        }
                      })
                    },1500)
              			uni.showToast({
              				title: res['data']['msg'],
              				icon: 'none'
              			});
                    this.loading = false
              		}
              	},
              	fail: () => {},
              	complete: () => {
              	}
              });
            },
      showImage(e) {
        // let imgPaths = [] 
        // imgPaths.push(e)
        // uni.previewImage({
        // 			current: 0,
        // 			urls: imgPaths,//图片路径是个数组，数组里面放图片的全路径
        // 			longPressActions: {  //长按保存图片到相册
        // 				itemList: ['保存图片'],
        // 				success: (data)=> {
        // 					uni.saveImageToPhotosAlbum({ //保存图片到相册
        // 						filePath: payUrl,
        // 						success: function () {
        // 							uni.showToast({icon:'success',title:'保存成功'})
        // 						},
        // 						fail: (err) => {
        // 							uni.showToast({icon:'none',title:'保存失败，请重新尝试'})
        // 						}
        // 					});
        // 				},
        // 				fail: (err)=> {
        // 					console.log(err.errMsg);
        // 				}
        // 		}
        // 	})
      },
      getdrawing(uid) {
        let timer = setTimeout(()=>{
            uni.request({
            	url: 'https://ai.iwangbang.com/draw/status?uid=' + uid,
            	method: 'GET',
            	header: {
            		'content-type': 'application/x-www-form-urlencoded', //自定义请求头信息
            		'token': uni.getStorageSync('wbyun_token'),
                'wbapp':'weixin_mp_xbgy'
            	},
            	data: {},
            	dataType: 'json',
            	success:  res => {
                console.log(res);
            		if (res['data']['code'] == 200) {
                    clearInterval(timer)
                    if(res.data.datas.data.cdn == undefined) {
                      this.getdrawing(uid)
                    }else if(  res.data.datas.data.cdn == '' ) {
                      this.msgList.splice(this.msgList.length - 1,1)
                        this.msgList.push({
                          msg: '当前咨询人数较多，请稍后再试...',
                          my:false
                        })
                        this.loading = false
                    }else {
                      this.msgList.splice(this.msgList.length - 1,1)
                        this.msgList.push({
                          msg: res.data.datas.data.cdn,
                          my:false
                        })
                        this.loading = false
                    }
            			return;
            		} else { 
            			uni.showToast({
            				title: res['data']['msg'],
            				icon: 'none'
            			});
            		}
            	},
            	fail: () => {},
            	complete: () => {
            	}
            });
        },1000)
      },

			mockReply() {
			
			}
		}
	}
</script>

<style >
	page {
		padding-bottom: 200upx;
	}

	.cu-chat .chat-avatar.cu-avatar {
	    width: 82upx;
	    height: 82upx;
	}
	.cu-item:not(.first) {
		padding-bottom: 0upx;
	}
	.cu-item.sec {
		padding-top: 0upx;
	}
  
	.main .content {
		word-wrap: break-word;
	}
	.foot {
/* 		padding-top: 20upx;
		padding-bottom: 0upx !important;
    margin-bottom: 0 !important; */
    display: flex !important;
	}
	.foot .cu-btn {
		margin-right: 20upx;
	}
	.foot .action.func {
		margin-left: 30upx;
	}
  
  .yhmsg>text {
    width: 100%;
  }
  .awaitts {
    width: 100%;
    height: 40rpx;
  }
  .cu-bar {
    height: 180rpx;
    background-color: rgb(246,250,252) !important;
   
  }
  .asfasd {
    flex: 1;
    margin: 0 20rpx;
    background-color: rgb(246,250,252);
    padding: 20rpx;
    font-size: 36rpx;
  }
  .padding-lr {
    /* height: 90rpx !important; */
     box-shadow: -10px -10px 50px 0px rgb(225 227 228);
  }
.repetition {
    display: flex;
    flex-direction: column;
    justify-content: center;
    text-align: center;
}
.hhbtn {
  width: 130rpx;
  height: 55rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: rgb(3,188,191);
  border-radius: 10rpx;
  margin: 10rpx 0;
  color: #fff;
}
.watermark {
  position: absolute;
  width: 90rpx;
  height: 45rpx;
  text-align: center;
  bottom: 0;
  right: 0;
  margin-right: 8%;
  margin-bottom: 8%;
  color: #fff;
  line-height: 45rpx;
  border-radius: 20rpx;
  font-size: 22rpx;
  opacity: 0.7;
  background-color: rgb(157,151,144);
}
</style>
